#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AI助手集成服务
整合语音转文本(ASR)和文本转回答(LLM)功能
"""

import json
import logging
from typing import Optional
from asr_file_service import FileTranscriptionService
from llm_service import LLMService

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class AIAssistantService:
    """AI助手集成服务"""
    
    def __init__(self, config_path: str = "config.json"):
        """初始化AI助手服务"""
        with open(config_path, 'r', encoding='utf-8') as f:
            self.config = json.load(f)
        
        # 初始化LLM服务
        llm_config = self.config['llm']
        self.llm_service = LLMService(
            api_key=llm_config['api_key'],
            base_url=llm_config['base_url'],
            model=llm_config['model']
        )
        
        logger.info("AI助手服务初始化完成")
    
    def process_audio_to_text(self, audio_file_path: str) -> str:
        """处理音频文件转文本"""
        logger.info(f"开始处理音频文件: {audio_file_path}")
        
        try:
            # 创建ASR服务实例
            asr_service = FileTranscriptionService(
                app_id=self.config['speech_to_text']['app_id'],
                access_key_id=self.config['speech_to_text']['access_key_id'],
                access_key_secret=self.config['speech_to_text']['access_key_secret'],
                audio_file_path=audio_file_path
            )
            
            # 执行转写
            text_result = asr_service.get_transcribe_result()
            logger.info(f"语音转文本结果: {text_result}")
            
            return text_result
            
        except Exception as e:
            logger.error(f"语音转文本失败: {e}")
            raise Exception(f"语音转文本失败: {e}")
    
    def process_text_to_response(self, text: str, stream: bool = False, 
                               enable_web_search: bool = False) -> str:
        """处理文本转回答"""
        logger.info(f"开始处理文本转回答: {text[:50]}...")
        
        try:
            # 使用LLM服务生成回答
            response = self.llm_service.chat(
                user_message=text,
                stream=stream,
                enable_web_search=enable_web_search
            )
            
            logger.info(f"文本转回答完成: {response[:50]}...")
            return response
            
        except Exception as e:
            logger.error(f"文本转回答失败: {e}")
            raise Exception(f"文本转回答失败: {e}")
    
    def process_audio_to_response(self, audio_file_path: str, stream: bool = False,
                                enable_web_search: bool = False) -> str:
        """完整的音频到回答流程"""
        logger.info("开始完整的音频到回答流程")
        
        try:
            # 步骤1: 语音转文本
            text = self.process_audio_to_text(audio_file_path)
            if not text.strip():
                return "抱歉，没有识别到有效的语音内容。"
            
            # 步骤2: 文本转回答
            response = self.process_text_to_response(
                text=text,
                stream=stream,
                enable_web_search=enable_web_search
            )
            
            return response
            
        except Exception as e:
            logger.error(f"完整流程处理失败: {e}")
            return f"处理失败: {e}"
    
    def get_conversation_history(self):
        """获取对话历史"""
        return self.llm_service.get_conversation_history()
    
    def clear_conversation_history(self):
        """清空对话历史"""
        self.llm_service.clear_conversation_history()
    
    def chat_with_text(self, text: str, stream: bool = False, 
                      enable_web_search: bool = False) -> str:
        """直接文本对话（不经过语音转文本）"""
        return self.process_text_to_response(
            text=text,
            stream=stream,
            enable_web_search=enable_web_search
        )


def main():
    """测试函数"""
    print("=== AI助手集成服务测试 ===")
    print("1. 测试语音转文本功能")
    print("2. 测试文本转回答功能")
    print("3. 测试完整音频到回答流程")
    print("4. 测试直接文本对话")
    print("5. 查看对话历史")
    print("6. 清空对话历史")
    print("0. 退出")
    
    # 创建AI助手服务
    ai_service = AIAssistantService()
    
    while True:
        try:
            choice = input("\n请选择功能 (0-6): ").strip()
            
            if choice == "0":
                print("退出程序")
                break
            elif choice == "1":
                # 测试语音转文本
                audio_file = input("请输入音频文件路径 (默认: test_1.pcm): ").strip()
                if not audio_file:
                    audio_file = "test_1.pcm"
                
                try:
                    text = ai_service.process_audio_to_text(audio_file)
                    print(f"转写结果: {text}")
                except Exception as e:
                    print(f"转写失败: {e}")
            
            elif choice == "2":
                # 测试文本转回答
                text = input("请输入要询问的文本: ").strip()
                if not text:
                    print("文本不能为空")
                    continue
                
                stream_mode = input("是否使用流式输出? (y/n, 默认n): ").strip().lower() == 'y'
                web_search = input("是否启用网络搜索? (y/n, 默认n): ").strip().lower() == 'y'
                
                try:
                    print("星火: ", end="")
                    response = ai_service.process_text_to_response(
                        text=text,
                        stream=stream_mode,
                        enable_web_search=web_search
                    )
                    if not stream_mode:
                        print(response)
                except Exception as e:
                    print(f"回答生成失败: {e}")
            
            elif choice == "3":
                # 测试完整流程
                audio_file = input("请输入音频文件路径 (默认: test_1.pcm): ").strip()
                if not audio_file:
                    audio_file = "test_1.pcm"
                
                stream_mode = input("是否使用流式输出? (y/n, 默认n): ").strip().lower() == 'y'
                web_search = input("是否启用网络搜索? (y/n, 默认n): ").strip().lower() == 'y'
                
                try:
                    print("星火: ", end="")
                    response = ai_service.process_audio_to_response(
                        audio_file_path=audio_file,
                        stream=stream_mode,
                        enable_web_search=web_search
                    )
                    if not stream_mode:
                        print(response)
                except Exception as e:
                    print(f"完整流程失败: {e}")
            
            elif choice == "4":
                # 直接文本对话
                text = input("请输入要询问的文本: ").strip()
                if not text:
                    print("文本不能为空")
                    continue
                
                stream_mode = input("是否使用流式输出? (y/n, 默认n): ").strip().lower() == 'y'
                web_search = input("是否启用网络搜索? (y/n, 默认n): ").strip().lower() == 'y'
                
                try:
                    print("星火: ", end="")
                    response = ai_service.chat_with_text(
                        text=text,
                        stream=stream_mode,
                        enable_web_search=web_search
                    )
                    if not stream_mode:
                        print(response)
                except Exception as e:
                    print(f"对话失败: {e}")
            
            elif choice == "5":
                # 查看对话历史
                history = ai_service.get_conversation_history()
                if not history:
                    print("暂无对话历史")
                else:
                    print("对话历史:")
                    for i, msg in enumerate(history):
                        role = "用户" if msg["role"] == "user" else "助手"
                        content = msg["content"][:100] + "..." if len(msg["content"]) > 100 else msg["content"]
                        print(f"{i+1}. {role}: {content}")
            
            elif choice == "6":
                # 清空对话历史
                ai_service.clear_conversation_history()
                print("对话历史已清空")
            
            else:
                print("无效选择，请重新输入")
                
        except KeyboardInterrupt:
            print("\n\n程序被用户中断")
            break
        except Exception as e:
            print(f"发生错误: {e}")


if __name__ == "__main__":
    main()
